package com.phone.servlet;

import com.phone.DBHelper;
import com.phone.ParameterCheck;
import com.phone.entity.Result;
import org.hibernate.Session;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by tisen on 2017/9/22.
 */
public abstract class SuperServlet extends HttpServlet {


    public static final String ERROR = "error";
    public static final String SUCCESS = "success";

    protected static final String ACTION = "action";
    protected Session session;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        session = DBHelper.getSession();
        ParameterCheck check = new ParameterCheck(request);
        JSONObject jsonObject = null;
        session.beginTransaction();
        try {
            jsonObject = Control(check, session);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
            Result result = new Result();
            result.setResult(ERROR);
            result.setReason(e.getMessage());
            jsonObject = new JSONObject(result);
        } finally {
            if (session != null && session.isOpen())
                session.close();
            out(response, jsonObject);
        }
    }

    protected abstract JSONObject Control(ParameterCheck check, Session session) throws Exception;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    private void out(HttpServletResponse response, JSONObject control) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println(control.toString());
        out.flush();
        out.close();
    }
}
